package servlet.User;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;

import com.jspsmart.upload.SmartUpload;
import service.room.RoomService;
import service.room.RoomServiceImpl;
import util.IpTimeStamp;


public class UserRegistered extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserRegistered() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        String username = null;
        String password = null;
        String phone = null;
        int community_id = 0;
        String housernum = null;
        String ownername = null;
        String house_img = null;
        RoomService roomService = new RoomServiceImpl();
        SmartUpload smart=new SmartUpload();
        try{
            //PageContext是jsp的内置对象，在servlet不能直接使用，需要做一些处理
            JspFactory _jspxFactory = null;
            PageContext pageContext = null;
            _jspxFactory = JspFactory.getDefaultFactory();
            pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true);

            smart.initialize(pageContext);//初始化上传操作
            // 设定上传限制
            // 1.限制每个上传文件的最大长度。

            // 2.限制总上传数据的长度。

            // 3.设定允许上传的文件（通过扩展名限制）,仅允许doc,txt文件。

            smart.upload();
            IpTimeStamp its=new IpTimeStamp(InetAddress.getLocalHost().getHostAddress());//request.getRemoteAddr()获得用户的ip地址
            //System.out.println("获取的ip为"+InetAddress.getLocalHost().getHostAddress());
            //如果要实现文件的批量上传，则只需用for循环，将getFile(0)中的0改为i即可
            String ext=smart.getFiles().getFile(0).getFileExt();//此为得到文件的扩展名,getFile(0)为得到唯一的一个上传文件
            if (ext != null&&ext !=""&&(!ext.equals(" "))) {
                String fileName = "Housecard" + its.getIpTimeRand() + "." + ext;
                //System.out.println("获取 的文件名为"+fileName);
                //this.getServletContext().getRealPath("/")为得到tomcat的跟目录，放于upload文件夹中，java.io.File.separator是一种安全操作
                //String realPath="";
                //this.getServletContext().getRealPath("/")+
                System.out.println(this.getServletContext().getRealPath("/") + "uploadFile" + java.io.File.separator + fileName);
                smart.getFiles().getFile(0).saveAs(this.getServletContext().getRealPath("/") + "uploadFile" + java.io.File.separator + fileName);
                System.out.println(this.getServletContext().getRealPath("/") + "uploadFile" + java.io.File.separator + fileName);
                house_img = "uploadFile/" + fileName + "";
            }
            //
            //由于前面的form表单已经进行了封装，这里就不能简单的用request.getparameter()来获取表单参数
            username = smart.getRequest().getParameter("username");//账号
            System.out.println(username);
            password = smart.getRequest().getParameter("password");
            phone = smart.getRequest().getParameter("phone");
            community_id = Integer.parseInt(smart.getRequest().getParameter("community"));
            housernum = smart.getRequest().getParameter("dong")+"栋"+smart.getRequest().getParameter("danyuan")+"单元"+smart.getRequest().getParameter("shi");
            ownername = smart.getRequest().getParameter("ownername");

        }catch(Exception e){
           e.printStackTrace(); //code
        }finally{
            // add this section
        }
        if (username==null||password==null||housernum==null||ownername==null||phone==null){
            System.out.println("删除，异常操作！");
            request.getRequestDispatcher("/admin/error/error404.jsp").forward(request,response);
        }if(house_img==null){
            request.setAttribute("message","未上传照片，注册失败");
            request.getRequestDispatcher("/app/registered/RegisteredForm.jsp").forward(request,response);
        }
        else {
            int i = roomService.RegisteredRoom(username, password, community_id, housernum, ownername, phone, house_img);
            String msg = null;
            if (i > 0) {
                msg = "success";
            } else {
                msg = "unSuccess";
            }
            response.sendRedirect(request.getContextPath() + "/index.jsp?msg=" + URLEncoder.encode(msg, "utf-8"));
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}